//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/download_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/my/local_file_model.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/mine/download_detail_widget.dart';
import 'package:hktk_app/widget/mine/download_share_page.dart';

/// 下载详情页面，资料下载
class DownloadDetailPage extends StatefulWidget {
  /// 行业名称
  final String industryName;

  /// 考试名称
  final String examName;

  /// 科目名称
  final String categoryName;

  const DownloadDetailPage({
    super.key,
    required this.industryName,
    required this.examName,
    required this.categoryName,
  });

  @override
  State<DownloadDetailPage> createState() => _DownloadDetailPageState();
}

class _DownloadDetailPageState extends State<DownloadDetailPage> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据
  late List<LocalFileModel> _list;

  @override
  void initState() {
    super.initState();
    debugPrint("downloadDetailPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("downloadDetailPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 异步加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      _list = await DownloadDao.getLocalFiles(
        industryName: widget.industryName,
        examName: widget.examName,
        categoryName: widget.categoryName,
      );

      map["suc"] = true;
    } catch (e) {
      debugPrint("downloadDetailPage 页面 -> _initData 方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("downloadDetailPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示组件
  _content() {
    if (_list.isNotEmpty) {
      var bottom = MediaQuery.of(_context).padding.bottom;
      return Container(
        margin: EdgeInsets.only(left: 20, right: 20, bottom: bottom),
        child: MediaQuery.removePadding(
          removeTop: true,
          context: _context,
          child: ListView.separated(
            itemBuilder: _itemBuilder,
            separatorBuilder: _separatorBuilder,
            itemCount: _list.length + 1,
          ),
        ),
      );
    } else {
      return showNoData();
    }
  }

  /// 列表显示组件
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _list.length) {
      LocalFileModel model = _list[index];
      return GestureDetector(
        onLongPress: () {
          debugPrint("downloadDetailPage 页面 -> 长按被触发 ===> 显示弹出框");
          // 暂时隐藏
          _downloadShowModel(context: context, model: model);
        },
        child: DownloadDetailWidget(
          model: model,
        ),
      );
      // return DownloadDetailWidget(
      //   model: model,
      // );
    } else {
      return showListEnd();
    }
  }

  /// 间距
  Widget _separatorBuilder(BuildContext context, int index) {
    return hiSpace(height: 20);
  }

  /// 显示弹出框
  void _downloadShowModel({
    required BuildContext context,
    required LocalFileModel model,
  }) {
    // 获取弹出层高度
    var height = MediaQuery.of(context).size.height;
    double sheetHeight = height * 0.2;

    // 弹出层
    showModalBottomSheet(
      context: context,
      // 设置底部弹出框全屏显示
      isScrollControlled: true,
      // 自定义弹出层高度
      constraints: BoxConstraints(maxHeight: sheetHeight),
      // 自定义圆角
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      builder: (BuildContext context) {
        return DownloadSharePage(model: model);
      },
    );
  }
}
